//
//  TimeSpaceViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 9/3/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "TimeSpaceViewController.h"

@interface TimeSpaceViewController ()

@end

@implementation TimeSpaceViewController
@synthesize scrollView = _scrollView;
@synthesize signal=_signal;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize NSDynamicLabelArray=_NSDynamicLabelArray;
@synthesize EWDynamicLabelArray=_EWDynamicLabelArray;
@synthesize linkList=_linkList;
@synthesize timer=_timer;
@synthesize GPSLocationList=_GPSLocationList;
@synthesize locationManager=_locationManager;
@synthesize direction=_direction;
@synthesize currentGPSLocation=_currentGPSLocation;
//@synthesize timeSpaceGPSView=_timeSpaceGPSView;
@synthesize timeSpaceView=_timeSpaceView;
@synthesize cycleTimerList=_cycleTimerList;
@synthesize tempString=tempString;
@synthesize startRecordingIndex=_startRecordingIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    self.view = [[[UIScrollView alloc] initWithFrame:self.view.frame] autorelease];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil agency:(Agency *)agency subsystem:(SubSystem *)subsystem timingPattern:(TimingPattern *)timingPattern signal:(Signal *)signal direction:(int)direction
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.startRecordingIndex=-1;
    self.direction=direction;
    if (self) {
        // Custom initialization
        self.GPSLocationList=[[[NSMutableArray alloc] init] autorelease];
        self.cycleTimerList=[[[NSMutableArray alloc] init] autorelease];
        self.agency=agency;
        self.subSystem=subsystem;
        self.timingPattern=timingPattern;
        self.signal=signal;
//        self.signal.agencyID=agency.agencyID;
//        self.signal.subSystemID=subsystem.subSystemID;
//        self.signal.timingPatternID=timingPattern.timingPatternID;
        self.linkList=[[[NSMutableArray alloc] init] autorelease];
        
        DynamicSignalLabel * dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:self.signal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
//        [dynamicLabel setLabelsExtensionNumber:3];
        
        DynamicSignalLabel * dynamicLabel2=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:self.signal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
//        [dynamicLabel2 setLabelsExtensionNumber:3];
        [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
        [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
        self.NSDynamicLabelArray=[[[NSMutableArray alloc] init] autorelease];
        self.EWDynamicLabelArray=[[[NSMutableArray alloc] init] autorelease];
        [self.NSDynamicLabelArray addObject:dynamicLabel];
        [self.EWDynamicLabelArray addObject:dynamicLabel2];
        Signal *currentSignal=self.signal;
        //northbound
        {
            currentSignal=self.signal;
            Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:0 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            while (nextSignal) {
                dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
                [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
                Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                if (!link) {
                    link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                }
                if (!link) {
                    continue;
                }
                [self.linkList addObject:link];
                dynamicLabel.frame = CGRectMake(0, [[self.NSDynamicLabelArray objectAtIndex:0] frame].origin.y-[link getOffsetY]-dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
                [dynamicLabel setAfterLink:link];
                [[self.NSDynamicLabelArray objectAtIndex:0] setBeforeLink:link];
                [self.NSDynamicLabelArray insertObject:dynamicLabel atIndex:0];

                currentSignal=nextSignal;
                nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:0 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
                
            }
        }
        //Southbound
        {
            currentSignal=self.signal;
            Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:180 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            while (nextSignal) {
                dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
                [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
//                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
                Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                if (!link) {
                    link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                }
                if (!link) {
                    continue;
                }
                [self.linkList addObject:link];
                dynamicLabel.frame = CGRectMake(0, [[self.NSDynamicLabelArray objectAtIndex:self.NSDynamicLabelArray.count-1] frame].origin.y+[link getOffsetY]+dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
                [dynamicLabel setBeforeLink:link];
                [[self.NSDynamicLabelArray objectAtIndex:self.NSDynamicLabelArray.count-1] setAfterLink:link];
                [self.NSDynamicLabelArray addObject:dynamicLabel];
                
                currentSignal=nextSignal;
                nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:180 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
                
            }
        }
        {
            DynamicSignalLabel * firstLabel=[self.NSDynamicLabelArray objectAtIndex:0];
            double differentce=abs(firstLabel.frame.origin.y);
            for (int k=0; k<self.NSDynamicLabelArray.count; k++) {
                
                DynamicSignalLabel * label=[self.NSDynamicLabelArray objectAtIndex:k];
                NSLog(@"\nbefore: %f",label.frame.origin.y);
                label.frame=CGRectMake(label.frame.origin.x, label.frame.origin.y+differentce, label.frame.size.width, label.frame.size.height);
                NSLog(@"\nafter: %f",label.frame.origin.y);
            }
        }
        //westbound
        {
            currentSignal=self.signal;
            Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:270 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            while (nextSignal) {
                dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
                [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
//                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
                Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                if (!link) {
                    link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                }
                if (!link) {
                    continue;
                }
                [self.linkList addObject:link];
                dynamicLabel.frame = CGRectMake(0, [[self.EWDynamicLabelArray objectAtIndex:0] frame].origin.y-[link getOffsetY]-dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
                [dynamicLabel setAfterLink:link];
                [[self.EWDynamicLabelArray objectAtIndex:0] setBeforeLink:link];
                [self.EWDynamicLabelArray insertObject:dynamicLabel atIndex:0];
                
                currentSignal=nextSignal;
                nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:270 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
                
            }
        }
        //eastbound
        {
            currentSignal=self.signal;
            Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:90 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            while (nextSignal) {
                dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
                [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
//                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
                Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                if (!link) {
                    link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
                }
                if (!link) {
                    continue;
                }
                [self.linkList addObject:link];
                dynamicLabel.frame = CGRectMake(0, [[self.EWDynamicLabelArray objectAtIndex:self.EWDynamicLabelArray.count-1] frame].origin.y+[link getOffsetY]+dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
                [dynamicLabel setBeforeLink:link];
                [[self.EWDynamicLabelArray objectAtIndex:self.EWDynamicLabelArray.count-1] setAfterLink:link];
                [self.EWDynamicLabelArray addObject:dynamicLabel];
                
                currentSignal=nextSignal;
                nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:90 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
                
            }
        }
        {
            DynamicSignalLabel * firstLabel=[self.EWDynamicLabelArray objectAtIndex:0];
            double differentce=abs(firstLabel.frame.origin.y);
            for (int k=0; k<self.EWDynamicLabelArray.count; k++) {
                
                DynamicSignalLabel * label=[self.EWDynamicLabelArray objectAtIndex:k];
                NSLog(@"\nbefore: %f",label.frame.origin.y);
                label.frame=CGRectMake(label.frame.origin.x, label.frame.origin.y+differentce, label.frame.size.width, label.frame.size.height);
                NSLog(@"\nafter: %f",label.frame.origin.y);
            }
        }
        
        
    }
    
    return self;
    
}

- (void)dealloc
{
    [_signal release];
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [_NSDynamicLabelArray release];
    [_EWDynamicLabelArray release];
    [_timer release];
    [_GPSLocationList release];
    [_locationManager release];
    [_scrollView release];
    [_timeSpaceView release];
    [_currentGPSLocation release];
    [_cycleTimerList release];
//    [_timeSpaceGPSView release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    UIScrollView *tempScrollView=(UIScrollView *)self.view;
    int viewHeight=0;
    if (self.NSDynamicLabelArray.count>1 && self.NSDynamicLabelArray.count>=self.EWDynamicLabelArray.count) {
        self.direction=NORTHBOUND;
        for (DynamicSignalLabel *signalLabel in self.NSDynamicLabelArray) {
            viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
        }
    }else if(self.EWDynamicLabelArray.count>1)
    {
        self.direction=EASTBOUND;
        for (DynamicSignalLabel *signalLabel in self.EWDynamicLabelArray) {
            viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
        }
    }
    
    viewHeight=viewHeight+50;
    tempScrollView.contentSize=CGSizeMake(640,viewHeight);
//    tempScrollView.contentInset=UIEdgeInsetsMake(64.0,0.0,44.0,0.0);
    switch (self.direction) {
        case NORTHBOUND:
        case SOUTHBOUND:
        {
            for (DynamicSignalLabel *label in self.NSDynamicLabelArray) {
                [self.view addSubview:label];
            }
        }
            break;
        case EASTBOUND:
        case WESTBOUND:
        {
            for (DynamicSignalLabel *label in self.EWDynamicLabelArray) {
                [self.view addSubview:label];
            }
        }
            break;
            
        default:
            break;
    }
    
    
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager setDelegate:self];
        [_locationManager setDistanceFilter:kCLDistanceFilterNone];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        //        [_locationManager startUpdatingLocation];
        //        [_locationManager startUpdatingHeading];
    }
    
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
//        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:cycle offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        //
        //        self.masterTimeLabel.text=[NSString stringWithFormat:@"              Master:%@ - %d",[TrafficSignalTimer getMasterTimeString:self.agency.baseTimeOffset], cycleTimer];;
//        for (DynamicSignalLabel* label in self.dynamicLabelArray) {
//            [label updateActivePhaseLabelWithMasterTime:cycleTimer];
//            
//        }
        UIScrollView *tempScrollView=(UIScrollView *)self.view;
        self.scrollView.showsHorizontalScrollIndicator = YES;
        self.scrollView.showsVerticalScrollIndicator = YES;
        switch (self.direction) {
            case NORTHBOUND:
            case SOUTHBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.NSDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
            case EASTBOUND:
            case WESTBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.EWDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
                
            default:
                break;
        }
        
//        self.timeSpaceGPSView=[[TimeSpaceGPSView alloc] initWithFrame:self.timeSpaceView.frame timeSpaceView:self.timeSpaceView];
        [self.view addSubview:self.timeSpaceView];
//        [self.view addSubview:self.timeSpaceGPSView];
        
//        [self.locationManager startUpdatingLocation];
    }
    
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
//    UIBarButtonItem *northSouthBoundButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
    CustomizedBarButtonItem *northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIcon.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
//    UIBarButtonItem *eastWestBoundButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(clickEastWestBoundButton:)] autorelease];
    CustomizedBarButtonItem *eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIcon.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
    switch (self.direction) {
        case NORTHBOUND:
        case SOUTHBOUND:
        {
            northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIconSelected.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
            eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIcon.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
        }
            break;
        case EASTBOUND:
        case WESTBOUND:
        {
            northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIcon.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
            eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIconSelected.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
        }
            break;
            
        default:
            break;
    }
    
    CustomizedBarButtonItem *panViewButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"pan-view.png"] target:self action:@selector(clickPanViewButton:)] autorelease];
    
    CustomizedBarButtonItem *recordButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"record.png"] target:self action:@selector(clickRecordGPSButton:)] autorelease];
    
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,northSouthBoundButton,space,eastWestBoundButton,space,panViewButton,space,recordButton,nil ];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Refresh_button.png"] style:UIBarButtonSystemItemAction target:self action:@selector(clickRefreshButton:)];
    
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void) updateTimer:(id) sender {
    
    
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
        
        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:cycle offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
//        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] time:[NSDate date] offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        if (self.currentGPSLocation) {
            [self.GPSLocationList addObject:[self getGPSEntity:self.currentGPSLocation cycleTimer:cycleTimer]];
            [self.cycleTimerList addObject:[NSNumber numberWithInt:cycleTimer]];
        }
//        
//        self.masterTimeLabel.text=[NSString stringWithFormat:@"              Master:%@ - %d",[TrafficSignalTimer getMasterTimeString:self.agency.baseTimeOffset], cycleTimer];;
//        for (DynamicSignalLabel* label in self.dynamicLabelArray) {
////            [label updateActivePhaseLabelWithMasterTime:cycleTimer];
//            [label updateActivePhaseLabelWithMasterTime:0];
//        }
        
//        [self.timeSpaceView removeFromSuperview];
        UIScrollView *tempScrollView=(UIScrollView *)self.view;
        if (!self.timeSpaceView) {
            switch (self.direction) {
                case NORTHBOUND:
                case SOUTHBOUND:
                {
                    self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.NSDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
                }
                    break;
                case EASTBOUND:
                case WESTBOUND:
                {
                    self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.EWDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
                }
                    break;
                    
                default:
                    break;
            }
            [self.view addSubview:self.timeSpaceView];
//            self.timeSpaceGPSView=[[TimeSpaceGPSView alloc] initWithFrame:self.timeSpaceView.frame timeSpaceView:self.timeSpaceView];
//            [self.view addSubview:self.timeSpaceGPSView];
        }else
        {
            [self.timeSpaceView setGPSLocationList:self.GPSLocationList];
            [self.timeSpaceView setCycleTimer:cycleTimer];
            [self.timeSpaceView setNeedsDisplay];
//            [self.timeSpaceGPSView setNeedsDisplay];
        }
    
//        [self.timeSpaceView drawRect:self.timeSpaceView.frame];
//        [self.timeSpaceView setNeedsDisplay];
        
    }
    
    //    [self updateRealTimeInformation];
    
}
- (void)viewDidUnload
{
    [self setScrollView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [self.timer invalidate];
    
    self.locationManager=nil;
    self.timer=nil;
    self.timeSpaceView=nil;
    self.currentGPSLocation=nil;
    self.cycleTimerList=nil;
//    self.timeSpaceGPSView=nil;
    
}
-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
    if (self.timer) {
        [self.timer invalidate];
        self.timer=nil;
        [self recordGPS];
    }
    
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.locationManager startUpdatingLocation];
    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.currentGPSLocation=newLocation;
//    [self simulateGPSReceiver:@"Chase Dr-Roseville Pkwy-East-20130725-19-46-46"];
    /*
    {
        if (!tempString) {
            NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDir = [documentPaths objectAtIndex:0];
            
            NSString * logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,@"University-19th St-20121019-16-53-21"] autorelease];
            NSString * fileContents=[[[NSString alloc] initWithContentsOfFile:logFilePath encoding:NSUTF8StringEncoding error:nil] autorelease];
            NSLog(@"\n%@",fileContents);
            self.tempString=fileContents;
            if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                return;
            }
            NSRange tempRange=[self.tempString rangeOfString:@"\n"];
            self.tempString=[self.tempString substringFromIndex:tempRange.location+1];
            if ([self.tempString rangeOfString:@","].location!=NSNotFound) {
                NSRange range=[self.tempString rangeOfString:@","];
                
                int cycleTimer=[[self.tempString substringToIndex:range.location] intValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double latitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double longitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                //        self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@"speed"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"speed"];
                self.tempString=[self.tempString substringFromIndex:range.location+6];
                
                if ([self.tempString rangeOfString:@"mps / course"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"mps / course"];
                double speed=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+12];
                
                if ([self.tempString rangeOfString:@") @"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@") @"];
                double course=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
                
//                [self.cycleTimerList addObject:[NSNumber numberWithInt:cycleTimer]];
                CLLocationCoordinate2D coordinate={latitude,longitude};
                self.currentGPSLocation=[[[CLLocation alloc] initWithCoordinate:(CLLocationCoordinate2D)coordinate altitude:0 horizontalAccuracy:5 verticalAccuracy:5 course:course speed:speed timestamp:newLocation.timestamp] autorelease];
                
                //            [self.GPSLocationList addObject:[self getGPSEntity:location cycleTimer:cycleTimer]];
                if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"\n"];
                
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
            }

        }else
        {
            NSRange tempRange=[self.tempString rangeOfString:@"\n"];
            self.tempString=[self.tempString substringFromIndex:tempRange.location+1];
            if ([self.tempString rangeOfString:@","].location!=NSNotFound) {
                NSRange range=[self.tempString rangeOfString:@","];
                
                int cycleTimer=[[self.tempString substringToIndex:range.location] intValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double latitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double longitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                //        self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@"speed"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"speed"];
                self.tempString=[self.tempString substringFromIndex:range.location+6];
                
                if ([self.tempString rangeOfString:@"mps / course"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"mps / course"];
                double speed=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+12];
                
                if ([self.tempString rangeOfString:@") @"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@") @"];
                double course=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
                
//                [self.cycleTimerList addObject:[NSNumber numberWithInt:cycleTimer]];
                CLLocationCoordinate2D coordinate={latitude,longitude};
                self.currentGPSLocation=[[[CLLocation alloc] initWithCoordinate:(CLLocationCoordinate2D)coordinate altitude:0 horizontalAccuracy:5 verticalAccuracy:5 course:course speed:speed timestamp:newLocation.timestamp] autorelease];
                
                //            [self.GPSLocationList addObject:[self getGPSEntity:location cycleTimer:cycleTimer]];
                if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"\n"];
                
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
            }

        }
    
            }*/
//    [self.GPSLocationList addObject:newLocation];
}

- (void) simulateGPSReceiver:(NSString *)documentName
{
    
        if (!tempString) {
            NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDir = [documentPaths objectAtIndex:0];
            
            NSString * logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,documentName] autorelease];
            NSString * fileContents=[[[NSString alloc] initWithContentsOfFile:logFilePath encoding:NSUTF8StringEncoding error:nil] autorelease];
            NSLog(@"\n%@",fileContents);
            self.tempString=fileContents;
            if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                return;
            }
            NSRange tempRange=[self.tempString rangeOfString:@"\n"];
            self.tempString=[self.tempString substringFromIndex:tempRange.location+1];
            if ([self.tempString rangeOfString:@","].location!=NSNotFound) {
                NSRange range=[self.tempString rangeOfString:@","];
                
                int cycleTimer=[[self.tempString substringToIndex:range.location] intValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double latitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double longitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                //        self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@"speed"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"speed"];
                self.tempString=[self.tempString substringFromIndex:range.location+6];
                
                if ([self.tempString rangeOfString:@"mps / course"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"mps / course"];
                double speed=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+12];
                
                if ([self.tempString rangeOfString:@") @"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@") @"];
                double course=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
                
                //                [self.cycleTimerList addObject:[NSNumber numberWithInt:cycleTimer]];
                CLLocationCoordinate2D coordinate={latitude,longitude};
                self.currentGPSLocation=[[[CLLocation alloc] initWithCoordinate:(CLLocationCoordinate2D)coordinate altitude:0 horizontalAccuracy:5 verticalAccuracy:5 course:course speed:speed timestamp:[NSDate date]] autorelease];
                
                //            [self.GPSLocationList addObject:[self getGPSEntity:location cycleTimer:cycleTimer]];
                if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"\n"];
                
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
            }
            
        }else
        {
            NSRange tempRange=[self.tempString rangeOfString:@"\n"];
            self.tempString=[self.tempString substringFromIndex:tempRange.location+1];
            if ([self.tempString rangeOfString:@","].location!=NSNotFound) {
                NSRange range=[self.tempString rangeOfString:@","];
                
                int cycleTimer=[[self.tempString substringToIndex:range.location] intValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double latitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@","].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@","];
                
                double longitude=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                //        self.tempString=[self.tempString substringFromIndex:range.location+1];
                if ([self.tempString rangeOfString:@"speed"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"speed"];
                self.tempString=[self.tempString substringFromIndex:range.location+6];
                
                if ([self.tempString rangeOfString:@"mps / course"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"mps / course"];
                double speed=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+12];
                
                if ([self.tempString rangeOfString:@") @"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@") @"];
                double course=[[self.tempString substringToIndex:range.location] floatValue];
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
                
                //                [self.cycleTimerList addObject:[NSNumber numberWithInt:cycleTimer]];
                CLLocationCoordinate2D coordinate={latitude,longitude};
                self.currentGPSLocation=[[[CLLocation alloc] initWithCoordinate:(CLLocationCoordinate2D)coordinate altitude:0 horizontalAccuracy:5 verticalAccuracy:5 course:course speed:speed timestamp:[NSDate date]] autorelease];
                
                //            [self.GPSLocationList addObject:[self getGPSEntity:location cycleTimer:cycleTimer]];
                if ([self.tempString rangeOfString:@"\n"].location==NSNotFound) {
                    return;
                }
                range=[self.tempString rangeOfString:@"\n"];
                
                self.tempString=[self.tempString substringFromIndex:range.location+1];
                
            }
            
        }
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) clickNorthSouthBoundButton:(id)sender
{
    self.direction=NORTHBOUND;
    NSMutableArray *tempaArray=[[[NSMutableArray alloc] initWithArray:self.toolbarItems] autorelease];
    CustomizedBarButtonItem *northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIconSelected.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
    CustomizedBarButtonItem *eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIcon.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
    [tempaArray replaceObjectAtIndex:2 withObject:northSouthBoundButton];
    [tempaArray replaceObjectAtIndex:4 withObject:eastWestBoundButton];
    self.toolbarItems=tempaArray;
    
    for (DynamicSignalLabel *label in self.EWDynamicLabelArray) {
        [label removeFromSuperview];
    }
    for (DynamicSignalLabel *label in self.NSDynamicLabelArray) {
        [self.view addSubview:label];
    }
    
    
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
        UIScrollView *tempScrollView=(UIScrollView *)self.view;
        int viewHeight=0;
        for (DynamicSignalLabel *signalLabel in self.NSDynamicLabelArray) {
            viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
        }
        viewHeight=viewHeight+50;
        tempScrollView.contentSize=CGSizeMake(640,viewHeight);
        [self.timeSpaceView removeFromSuperview];
        switch (self.direction) {
            case NORTHBOUND:
            case SOUTHBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.NSDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
            case EASTBOUND:
            case WESTBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.EWDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
                
            default:
                break;
        }
        //        self.timeSpaceGPSView=[[TimeSpaceGPSView alloc] initWithFrame:self.timeSpaceView.frame timeSpaceView:self.timeSpaceView];
        [self.view addSubview:self.timeSpaceView];
    }
}

- (void) clickEastWestBoundButton:(id)sender
{
    self.direction=EASTBOUND;
    NSMutableArray *tempaArray=[[[NSMutableArray alloc] initWithArray:self.toolbarItems] autorelease];
    CustomizedBarButtonItem *northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIcon.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
    CustomizedBarButtonItem *eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIconSelected.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
    [tempaArray replaceObjectAtIndex:2 withObject:northSouthBoundButton];
    [tempaArray replaceObjectAtIndex:4 withObject:eastWestBoundButton];
    self.toolbarItems=tempaArray;
    for (DynamicSignalLabel *label in self.NSDynamicLabelArray) {
        [label removeFromSuperview];
    }
    for (DynamicSignalLabel *label in self.EWDynamicLabelArray) {
        [self.view addSubview:label];
    }
    
    
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
        UIScrollView *tempScrollView=(UIScrollView *)self.view;
        int viewHeight=0;
        for (DynamicSignalLabel *signalLabel in self.EWDynamicLabelArray) {
            viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
        }
        viewHeight=viewHeight+50;
        tempScrollView.contentSize=CGSizeMake(640,viewHeight);
        [self.timeSpaceView removeFromSuperview];
        switch (self.direction) {
            case NORTHBOUND:
            case SOUTHBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.NSDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
            case EASTBOUND:
            case WESTBOUND:
            {
                self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.EWDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
            }
                break;
                
            default:
                break;
        }
        //        self.timeSpaceGPSView=[[TimeSpaceGPSView alloc] initWithFrame:self.timeSpaceView.frame timeSpaceView:self.timeSpaceView];
        [self.view addSubview:self.timeSpaceView];
    }
}
- (void) clickPanViewButton:(id)sender
{
    if (self.timeSpaceView.isAutomaticPan) {
        self.timeSpaceView.isAutomaticPan=NO;
        NSMutableArray *tempArray=[[NSMutableArray alloc] initWithArray:self.toolbarItems];
        CustomizedBarButtonItem *panViewButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"pan-view.png"] target:self action:@selector(clickPanViewButton:)] autorelease];
        [tempArray replaceObjectAtIndex:6 withObject:panViewButton];
        self.toolbarItems=tempArray;
        
        
    }else
    {
        self.timeSpaceView.isAutomaticPan=YES;
        NSMutableArray *tempArray=[[NSMutableArray alloc] initWithArray:self.toolbarItems];
        CustomizedBarButtonItem *panViewButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"pan-view-blocked.png"] target:self action:@selector(clickPanViewButton:)] autorelease];
        [tempArray replaceObjectAtIndex:6 withObject:panViewButton];
        self.toolbarItems=tempArray;
    }
}
- (void) clickRefreshButton:(id)sender
{
    //re init
    
    self.GPSLocationList=[[[NSMutableArray alloc] init] autorelease];
    self.cycleTimerList=[[[NSMutableArray alloc] init] autorelease];
//    self.agency=agency;
//    self.subSystem=subsystem;
//    self.timingPattern=timingPattern;
//    self.signal=signal;
    //        self.signal.agencyID=agency.agencyID;
    //        self.signal.subSystemID=subsystem.subSystemID;
    //        self.signal.timingPatternID=timingPattern.timingPatternID;
    self.linkList=[[[NSMutableArray alloc] init] autorelease];
    
    DynamicSignalLabel * dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:self.signal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
    //        [dynamicLabel setLabelsExtensionNumber:3];
    
    DynamicSignalLabel * dynamicLabel2=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:self.signal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
    //        [dynamicLabel2 setLabelsExtensionNumber:3];
    [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
    [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
    self.NSDynamicLabelArray=[[[NSMutableArray alloc] init] autorelease];
    self.EWDynamicLabelArray=[[[NSMutableArray alloc] init] autorelease];
    [self.NSDynamicLabelArray addObject:dynamicLabel];
    [self.EWDynamicLabelArray addObject:dynamicLabel2];
    Signal *currentSignal=self.signal;
    //northbound
    {
        currentSignal=self.signal;
        Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:0 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
        while (nextSignal) {
            dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
            [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
            Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            if (!link) {
                link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            }
            if (!link) {
                continue;
            }
            [self.linkList addObject:link];
            dynamicLabel.frame = CGRectMake(0, [[self.NSDynamicLabelArray objectAtIndex:0] frame].origin.y-[link getOffsetY]-dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
            [dynamicLabel setAfterLink:link];
            [[self.NSDynamicLabelArray objectAtIndex:0] setBeforeLink:link];
            [self.NSDynamicLabelArray insertObject:dynamicLabel atIndex:0];
            
            currentSignal=nextSignal;
            nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:0 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            
        }
    }
    //Southbound
    {
        currentSignal=self.signal;
        Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:180 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
        while (nextSignal) {
            dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:NORTHBOUND labelsExtensionNumber:3] autorelease];
            [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
            //                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
            Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            if (!link) {
                link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            }
            if (!link) {
                continue;
            }
            [self.linkList addObject:link];
            dynamicLabel.frame = CGRectMake(0, [[self.NSDynamicLabelArray objectAtIndex:self.NSDynamicLabelArray.count-1] frame].origin.y+[link getOffsetY]+dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
            [dynamicLabel setBeforeLink:link];
            [[self.NSDynamicLabelArray objectAtIndex:self.NSDynamicLabelArray.count-1] setAfterLink:link];
            [self.NSDynamicLabelArray addObject:dynamicLabel];
            
            currentSignal=nextSignal;
            nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:180 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            
        }
    }
    {
        DynamicSignalLabel * firstLabel=[self.NSDynamicLabelArray objectAtIndex:0];
        double differentce=abs(firstLabel.frame.origin.y);
        for (int k=0; k<self.NSDynamicLabelArray.count; k++) {
            
            DynamicSignalLabel * label=[self.NSDynamicLabelArray objectAtIndex:k];
            NSLog(@"\nbefore: %f",label.frame.origin.y);
            label.frame=CGRectMake(label.frame.origin.x, label.frame.origin.y+differentce, label.frame.size.width, label.frame.size.height);
            NSLog(@"\nafter: %f",label.frame.origin.y);
        }
    }
    //westbound
    {
        currentSignal=self.signal;
        Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:270 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
        while (nextSignal) {
            dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
            [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
            //                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
            Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            if (!link) {
                link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            }
            if (!link) {
                continue;
            }
            [self.linkList addObject:link];
            dynamicLabel.frame = CGRectMake(0, [[self.EWDynamicLabelArray objectAtIndex:0] frame].origin.y-[link getOffsetY]-dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
            [dynamicLabel setAfterLink:link];
            [[self.EWDynamicLabelArray objectAtIndex:0] setBeforeLink:link];
            [self.EWDynamicLabelArray insertObject:dynamicLabel atIndex:0];
            
            currentSignal=nextSignal;
            nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:270 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            
        }
    }
    //eastbound
    {
        currentSignal=self.signal;
        Signal * nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:90 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
        while (nextSignal) {
            dynamicLabel=[[[DynamicSignalLabel alloc] initWithSignal:0 reuseIdentifier:nil signal:nextSignal direction:EASTBOUND labelsExtensionNumber:3] autorelease];
            [dynamicLabel updateActivePhaseLabelWithMasterTime:0];
            //                [dynamicLabel2 updateActivePhaseLabelWithMasterTime:0];
            Link * link=[GeometryCalculation getlinkBetweenTwoIntersections:nextSignal.signalID intersection2ID:currentSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            if (!link) {
                link=[GeometryCalculation getlinkBetweenTwoIntersections:currentSignal.signalID intersection2ID:nextSignal.signalID subSystemID:self.subSystem.subSystemID agencyID:self.agency.agencyID];
            }
            if (!link) {
                continue;
            }
            [self.linkList addObject:link];
            dynamicLabel.frame = CGRectMake(0, [[self.EWDynamicLabelArray objectAtIndex:self.EWDynamicLabelArray.count-1] frame].origin.y+[link getOffsetY]+dynamicLabel.activePhaseLabel.frame.size.height, dynamicLabel.frame.size.width, dynamicLabel.frame.size.height);
            [dynamicLabel setBeforeLink:link];
            [[self.EWDynamicLabelArray objectAtIndex:self.EWDynamicLabelArray.count-1] setAfterLink:link];
            [self.EWDynamicLabelArray addObject:dynamicLabel];
            
            currentSignal=nextSignal;
            nextSignal=[GeometryCalculation calculateNextSignal:currentSignal heading:90 agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern];
            
        }
    }
    {
        DynamicSignalLabel * firstLabel=[self.EWDynamicLabelArray objectAtIndex:0];
        double differentce=abs(firstLabel.frame.origin.y);
        for (int k=0; k<self.EWDynamicLabelArray.count; k++) {
            
            DynamicSignalLabel * label=[self.EWDynamicLabelArray objectAtIndex:k];
            NSLog(@"\nbefore: %f",label.frame.origin.y);
            label.frame=CGRectMake(label.frame.origin.x, label.frame.origin.y+differentce, label.frame.size.width, label.frame.size.height);
            NSLog(@"\nafter: %f",label.frame.origin.y);
        }
    }

    
    {
        int cycle=[self.timingPattern.cycleLength intValue];
        if (cycle>10) {
            UIScrollView *tempScrollView=(UIScrollView *)self.view;
            int viewHeight=0;
            for (DynamicSignalLabel *signalLabel in self.EWDynamicLabelArray) {
                viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
            }
            viewHeight=viewHeight+50;
            tempScrollView.contentSize=CGSizeMake(640,viewHeight);
            [self.timeSpaceView removeFromSuperview];
            switch (self.direction) {
                case NORTHBOUND:
                case SOUTHBOUND:
                {
                    int viewHeight=0;
                    for (DynamicSignalLabel *signalLabel in self.NSDynamicLabelArray) {
                        viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
                    }
                    viewHeight=viewHeight+50;
                    tempScrollView.contentSize=CGSizeMake(640,viewHeight);
                    self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.NSDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
                }
                    break;
                case EASTBOUND:
                case WESTBOUND:
                {
                    int viewHeight=0;
                    for (DynamicSignalLabel *signalLabel in self.EWDynamicLabelArray) {
                        viewHeight=viewHeight+signalLabel.frame.size.height+[signalLabel.afterLink getOffsetY];
                    }
                    viewHeight=viewHeight+50;
                    tempScrollView.contentSize=CGSizeMake(640,viewHeight);
                    self.timeSpaceView=[[[TimeSpaceView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, tempScrollView.contentSize.width, tempScrollView.contentSize.height) dynamicSignalLabelList:self.EWDynamicLabelArray direction:self.direction agency:self.agency timingPattern:self.timingPattern] autorelease];
                }
                    break;
                    
                default:
                    break;
            }
            //        self.timeSpaceGPSView=[[TimeSpaceGPSView alloc] initWithFrame:self.timeSpaceView.frame timeSpaceView:self.timeSpaceView];
            [self.view addSubview:self.timeSpaceView];
        }

    }

}
- (void) clickRecordGPSButton:(id)sender
{
    
    CustomizedBarButtonItem *recordButton=nil;
    if (self.startRecordingIndex>0) {
        
        recordButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"record.png"] target:self action:@selector(clickRecordGPSButton:)] autorelease];
        [self recordGPS];
        self.startRecordingIndex=-1;
    }else
    {
        if (self.GPSLocationList.count<1) {
            self.startRecordingIndex=0;
        }
        self.startRecordingIndex=self.GPSLocationList.count-1;
        recordButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"stoprecording.png"] target:self action:@selector(clickRecordGPSButton:)] autorelease];
    }
//    self.timeSpaceView.isAutomaticPan=YES;
    NSMutableArray *tempArray=[[NSMutableArray alloc] initWithArray:self.toolbarItems];
    [tempArray replaceObjectAtIndex:8 withObject:recordButton];
    self.toolbarItems=tempArray;
    
//    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
//    //    UIBarButtonItem *northSouthBoundButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
//    CustomizedBarButtonItem *northSouthBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"NorthboundSouthboundIcon.png"] target:self action:@selector(clickNorthSouthBoundButton:)] autorelease];
//    //    UIBarButtonItem *eastWestBoundButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(clickEastWestBoundButton:)] autorelease];
//    CustomizedBarButtonItem *eastWestBoundButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"EastboundWestboundIcon.png"] target:self action:@selector(clickEastWestBoundButton:)] autorelease];
//    
//    CustomizedBarButtonItem *panViewButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"pan-view.png"] target:self action:@selector(clickPanViewButton:)] autorelease];
//    
//    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
//    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,northSouthBoundButton,space,eastWestBoundButton,space,panViewButton,space,recordButton,nil ];

}
-(void) recordGPS
{
    if (self.startRecordingIndex==-1) {
        return;
    }
    if (self.GPSLocationList.count<=0) {
        return;
    }
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSDate *time=[NSDate date];
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyyMMdd-HH-mm-ss"];
    NSString *stringFromDate = [formatter stringFromDate:time];
    NSString *intersectionName=[NSString stringWithString:self.signal.signalName];
    intersectionName=[intersectionName stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    NSRange range=[intersectionName rangeOfString:@"/"];
    GPSEntity * location=[self.GPSLocationList objectAtIndex:0];
    NSString * direction;
    if (location.location.course<45||location.location.course>=315){
        direction=@"North";
    }else if (location.location.course>=45||location.location.course<135)
    {
        direction=@"East";
    }else if (location.location.course>=135||location.location.course<225)
    {
        direction=@"South";
        
    }else if (location.location.course>=225||location.location.course<315)
    {
        direction=@"West";
    }
    NSString * logFilePath=nil;
    if (range.location == NSNotFound) {
        logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@-%@-%@.gps",documentsDir,intersectionName,direction,stringFromDate] autorelease];
    }else
    {
        logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@-%@-%@-%@.gps",documentsDir,[intersectionName substringToIndex:range.location],direction,[intersectionName substringFromIndex:range.location+1],stringFromDate] autorelease];
    }
//    NSString * logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@-%@-%@.gps",documentsDir,[intersectionName substringToIndex:range.location],[intersectionName substringFromIndex:range.location+1],stringFromDate] autorelease];
    
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logFilePath];
    if (!fileHandler) {
        NSString *content=[NSString stringWithFormat:@"GPS logs from iphone beginning at the time of %@, at the intersection of %@\n",stringFromDate,self.signal.signalName];
        NSData* data=[content dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",logFilePath);
        if(![data writeToFile:logFilePath atomically:YES ])
        {
            return;
        }
        fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logFilePath];
    }
    [fileHandler seekToEndOfFile];
    if (self.cycleTimerList.count!=self.GPSLocationList.count) {
        return;
    }
    for (int i=self.startRecordingIndex; i<self.GPSLocationList.count; i++) {
        GPSEntity * currentLocation=[self.GPSLocationList objectAtIndex:i];
        NSLog(@"%d,%f,%f\n",[[self.cycleTimerList objectAtIndex:i] intValue],currentLocation.location.coordinate.latitude,currentLocation.location.coordinate.longitude);
        NSString *content=[NSString stringWithFormat:@"%d,%f,%f,%@\n",[[self.cycleTimerList objectAtIndex:i] intValue],currentLocation.location.coordinate.latitude,currentLocation.location.coordinate.longitude,currentLocation.location.description];
        NSData* data=[content dataUsingEncoding:NSUTF8StringEncoding];
        
        [fileHandler writeData:data];
    }
    
    [fileHandler closeFile];
}


-(GPSEntity *)getGPSEntity:(CLLocation *)location cycleTimer:(int)cycleTimer
{
    //    int locationOffset=-200;
    double timeToPixel=0;
    double distanceToY=0;
    timeToPixel=320.0f/[[self.timingPattern cycleLength] intValue];;
    //Northbound and southbound
    double NSx=-1;
    double NSy=-1;
    if (cycleTimer>self.timeSpaceView.countedTotalTime) {
        NSx=round(cycleTimer*timeToPixel);
    }else
    {
        
        int difference=self.timeSpaceView.countedTotalTime;
        while (difference>=[self.timingPattern.cycleLength intValue]) {
            difference=difference-[self.timingPattern.cycleLength intValue];
        }
        if (cycleTimer>difference) {
            NSx=round((self.timeSpaceView.countedTotalTime+(cycleTimer-difference))*timeToPixel);
        }
        
    }
//    int temp2=[[[self.GPSLocationList lastObject] NSInterfacePoint] X];
//    double temp=cycleTimer>=(double)[[[self.GPSLocationList lastObject] NSInterfacePoint] X]/timeToPixel;
//    if (self.cycleTimerList.count<=0 || cycleTimer>=((double)[[[self.GPSLocationList lastObject] NSInterfacePoint] X]/timeToPixel)) {
//        NSx=round(cycleTimer*timeToPixel);
//    }else
//    {
//        int tempCycleTimer=cycleTimer;
//        while (tempCycleTimer<((double)[[[self.GPSLocationList lastObject] NSInterfacePoint] X]/timeToPixel)) {
//            tempCycleTimer=tempCycleTimer+[self.timingPattern.cycleLength intValue];
//        }
//        NSx=round(tempCycleTimer*timeToPixel);
//    }

    DynamicSignalLabel * southLabel=nil;
    {
        if (self.NSDynamicLabelArray.count<=0) {
            return nil;
        }
        DynamicSignalLabel * label=[self.NSDynamicLabelArray objectAtIndex:0] ;
        timeToPixel=320.0f/[[self.timingPattern cycleLength] intValue];
        if (label.beforeLink) {
            distanceToY=(float)label.beforeLink.getOffsetY/((float)[label.beforeLink.length intValue]*0.3048);
        }else if (label.afterLink)
        {
            distanceToY=(float)label.afterLink.getOffsetY/((float)[label.afterLink.length intValue]*0.3048);
        }
        
        
        Intersection * intersection=nil;
        
        
        
        for (int i=0;i<self.NSDynamicLabelArray.count;i++) {
            label=[self.NSDynamicLabelArray objectAtIndex:i];
            intersection=[XMLParser getIntersection:label.signal.signalID agencyID:label.signal.agencyID subSystemID:label.signal.subSystemID];
            if (intersection.intersectionCoordinate.latitude<location.coordinate.latitude) {
                southLabel=label;
                break;
                
            }
        }
        //            Link *beforeLink=lastLabel.beforeLink;
        //            InterfacePoint *temppoint=nil;
        //            if (label.nbandLeftBeginPoints.count<=0) {
        //                continue;
        //            }
        if (self.GPSLocationList.count<=0) {
//            NSx=round(cycleTimer*timeToPixel);
            NSy=-1;
            if (southLabel) {
                NSy=southLabel.frame.origin.y+southLabel.signalNameLabel.frame.size.height-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
            }else
            {
                NSy=label.frame.origin.y+label.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
            }
            
        }else
        {
            GPSEntity *lastGPS=[self.GPSLocationList lastObject];
            if (location.course>270||location.course<90) {
                
                if ((!southLabel&&!lastGPS.southLabel)||([southLabel.signal.signalName isEqualToString:lastGPS.southLabel.signal.signalName])) {
//                    //NSx=round(cycleTimer*timeToPixel);
                    NSy=lastGPS.NSInterfacePoint.Y-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastGPS.location.coordinate];
                }else
                {
                    //NSx=round(cycleTimer*timeToPixel);
                    if (southLabel) {
                        NSy=southLabel.frame.origin.y+southLabel.signalNameLabel.frame.size.height-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }else
                    {
                        NSy=label.frame.origin.y+label.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }
                    
                }
            }else
            {
                if ((!southLabel&&!lastGPS.southLabel)||([southLabel.signal.signalName isEqualToString:lastGPS.southLabel.signal.signalName])) {
                    //NSx=round(cycleTimer*timeToPixel);
                    NSy=lastGPS.NSInterfacePoint.Y+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastGPS.location.coordinate];
                }else
                {
                    //NSx=round(cycleTimer*timeToPixel);
                    if (southLabel) {
                        Intersection *lastIntersection=[XMLParser getIntersection:lastGPS.southLabel.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
                        NSy=lastGPS.southLabel.frame.origin.y+lastGPS.southLabel.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastIntersection.intersectionCoordinate];
                    }else
                    {
                        NSy=label.frame.origin.y+label.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }
                    
                }
            }
        }
    }
    //Westbound and eastbound
    double EWx=-1;
    double EWy=-1;
    if (cycleTimer>self.timeSpaceView.countedTotalTime) {
        EWx=round(cycleTimer*timeToPixel);
    }else
    {
        
        int difference=self.timeSpaceView.countedTotalTime;
        while (difference>=[self.timingPattern.cycleLength intValue]) {
            difference=difference-[self.timingPattern.cycleLength intValue];
        }
        if (cycleTimer>difference) {
            EWx=round((self.timeSpaceView.countedTotalTime+(cycleTimer-difference))*timeToPixel);
        }
        
    }
//    if (self.cycleTimerList.count<=0 || cycleTimer>=[[self.cycleTimerList lastObject] integerValue]) {
//        EWx=round(cycleTimer*timeToPixel);
//    }else
//    {
//        int tempCycleTimer=cycleTimer;
//        while (tempCycleTimer<[[self.cycleTimerList lastObject] integerValue]) {
//            tempCycleTimer=tempCycleTimer+[self.timingPattern.cycleLength intValue];
//        }
//        EWx=round(tempCycleTimer*timeToPixel);
//    }
    DynamicSignalLabel * EastLabel=nil;
    {
        if (self.EWDynamicLabelArray.count<=0) {
            return nil;
        }
        DynamicSignalLabel * label=[self.EWDynamicLabelArray objectAtIndex:0] ;
        timeToPixel=320.0f/[[self.timingPattern cycleLength] intValue];
        if (label.beforeLink) {
            distanceToY=(float)label.beforeLink.getOffsetY/((float)[label.beforeLink.length intValue]*0.3048);
        }else if (label.afterLink)
        {
            distanceToY=(float)label.afterLink.getOffsetY/((float)[label.afterLink.length intValue]*0.3048);
        }
        
        
        Intersection * intersection=nil;
        
        
        
        for (int i=0;i<self.EWDynamicLabelArray.count;i++) {
            label=[self.EWDynamicLabelArray objectAtIndex:i];
            intersection=[XMLParser getIntersection:label.signal.signalID agencyID:label.signal.agencyID subSystemID:label.signal.subSystemID];
            if (intersection.intersectionCoordinate.longitude>location.coordinate.longitude) {
                EastLabel=label;
                break;
                
            }
        }
        //            Link *beforeLink=lastLabel.beforeLink;
        //            InterfacePoint *temppoint=nil;
        //            if (label.nbandLeftBeginPoints.count<=0) {
        //                continue;
        //            }
        if (self.GPSLocationList.count<=0) {
//            EWx=round(cycleTimer*timeToPixel);
            EWy=-1;
            if (EastLabel) {
                EWy=EastLabel.frame.origin.y+EastLabel.signalNameLabel.frame.size.height-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
            }else
            {
                EWy=label.frame.origin.y+label.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
            }
            
        }else
        {
            GPSEntity *lastGPS=[self.GPSLocationList lastObject];
            if (location.course>180) {
                
                if ((!EastLabel&&!lastGPS.eastLabel)||([EastLabel.signal.signalName isEqualToString:lastGPS.eastLabel.signal.signalName])) {
//                    EWx=round(cycleTimer*timeToPixel);
                    EWy=lastGPS.EWInterfacePoint.Y-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastGPS.location.coordinate];
                }else
                {
//                    EWx=round(cycleTimer*timeToPixel);
                    if (EastLabel) {
                        EWy=EastLabel.frame.origin.y+EastLabel.signalNameLabel.frame.size.height-distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }else
                    {
                        EWy=label.frame.origin.y+label.signalNameLabel.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }
                    
                }
            }else
            {
                if ((!EastLabel&&!lastGPS.eastLabel)||([EastLabel.signal.signalName isEqualToString:lastGPS.eastLabel.signal.signalName])) {
//                    EWx=round(cycleTimer*timeToPixel);
                    EWy=lastGPS.EWInterfacePoint.Y+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastGPS.location.coordinate];
                }else
                {
//                    EWx=round(cycleTimer*timeToPixel);
                    if (EastLabel) {
                        Intersection *lastIntersection=[XMLParser getIntersection:lastGPS.eastLabel.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
                        EWy=lastGPS.eastLabel.frame.origin.y+lastGPS.eastLabel.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:lastIntersection.intersectionCoordinate];
                    }else
                    {
                        EWy=label.frame.origin.y+label.frame.size.height+distanceToY*[GeometryCalculation distanceOfTwoCoordinates:location.coordinate coordB:intersection.intersectionCoordinate];
                    }
                    
                }
            }
        }
    }
    
    GPSEntity *gpsEntity=[[[GPSEntity alloc] initWithLocation:location NSInterfacePoint:[[[InterfacePoint alloc] initWithXY:NSx Y:NSy] autorelease] EWInterfacePoint:[[[InterfacePoint alloc] initWithXY:EWx Y:EWy] autorelease] southLabel:southLabel eastLabel:EastLabel] autorelease];
    return gpsEntity;
    
}



@end
